package com.lj.framework.web.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lj.framework.common.base.auth.LoginAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisTemplate redisCache;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;


    public LoginAdmin getLoginUser(String token){
        if (StringUtils.isEmpty(token)){
            return null;
        }
        try{
            Algorithm algorithm = Algorithm.HMAC512(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("lj").build();
            DecodedJWT jwt = verifier.verify(token);
            String uid = jwt.getClaim("login_user").asString();
            if (!redisCache.hasKey(uid)){
                return null;
            }
            redisCache.expire(uid, expireTime, TimeUnit.MINUTES);
            return (LoginAdmin) redisCache.opsForValue().get(uid);
        }catch (JWTVerificationException e){
            e.printStackTrace();
            return null;
        }
    }

    public String createToken(LoginAdmin loginAdmin){
        try{
            String uid = UUID.randomUUID().toString().replace("-", "");

            Algorithm algorithm = Algorithm.HMAC512(secret);
            String token =  JWT.create().withIssuer("lj")
                    .withIssuedAt(new Date())
                    .withClaim("login_user", uid)
                    .sign(algorithm);
            //同时设置到期时间
            redisCache.opsForValue().set(uid, loginAdmin, expireTime, TimeUnit.MINUTES);
            return token;
        }catch (JWTCreationException e){
            e.printStackTrace();
            return null;
        }
    }

}
